import network
import socket
from time import sleep
from picozero import pico_temp_sensor, pico_led
import machine
import requests
ssid = 'MIT'
password = '3pj@t_gwUp'
html_css_code = """
LED is {{ state }}
Temperature is: {{ temperature }}
Quote of the day is {{ quote }}
Current Weather
Weather in {{ city_name }}:
Weather: {{ weather_data }}:
Latest News
News Title 1
News content goes here. Provide a brief description of the news story.
News Title 2
News content goes here. Provide a brief description of the news story.
"""
def connect():
# Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Waiting for connection...')
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
# Open a socket
address = (ip, 8080)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def get_weather_data(api_key, city):
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
#print(response)
#print('hello')
return response.json()
def webpage(temperature, state, quote, weather_data, city_name):
# Replace placeholders with actual values
html = html_css_code.replace('{{ state }}', state)
html = html.replace('{{ temperature }}', str(temperature))
html = html.replace('{{ quote }}', quote)
html = html.replace('{{ city_name }}', city_name)
html = html.replace('{{ weather_data }}', weather_data['weather'][0]['description'])
return html
def serve(connection):
# Start a web server
state = 'OFF'
pico_led.off()
temperature = 0
quote = ''
# Define city_name here
city_name = 'boston' # Replace with the actual city name you want weather information for
weather_data = get_weather_data('bd4cf9b348a3a1bb5cf2fab8c40d5676', city_name) # Replace with your actual API key
print(weather_data)
print('hi')
try:
response = requests.get('https://zenquotes.io/api/random')
if response.status_code == 200:
data = response.json()[0]
quote = data['q'] + ' - ' + data['a']
print('got quote:', quote)
else:
print('Failed to retrieve quote. Status code:', response.status_code)
except Exception as ex:
print('An unexpected error occurred:', ex)
while True:
client = connection.accept()[0]
request = client.recv(1024)
request = str(request)
try:
request = request.split()[1]
except IndexError:
pass
print('Received request:', request)
if request == '/lighton?':
print("Turning LED on...")
pico_led.on()
state = 'ON'
elif request == '/lightoff?':
print("Turning LED off...")
pico_led.off()
state = 'OFF'
temperature = pico_temp_sensor.temp
html = webpage(temperature, state, quote, weather_data, city_name)
response = f"HTTP/1.1 200 OK\nContent-Length: {len(html)}\n\n{html}"
client.send(response)
client.close()
try:
ip = connect()
connection = open_socket(ip)
serve(connection)
except KeyboardInterrupt:
machine.reset()